import http from '../utils/http.js'
import { findStudentScoreInfo, mapScoreInfoData } from './checkLearningStatus.js'

const API_PATHS = {
  FIND_SUBJECT_DIFFICULTY: '/jsonrest/mobile/score/AnalysisReportScore/0/findStudentAnalysisSubjectDifficulty',
  GET_KNOWLEDGE_ANALYSIS: '/jsonrest/mobile/score/AnalysisReportScore/0/getKnowledgePointAnalysis',
  FIND_XDJP_FOR_COURSE: '/jsonrest/mobile/score/AnalysisReportScore/0/findXDJPForCourse'
}

const SUBJECT_REPORT_STORAGE_KEY = 'checkingLearningStatus:subjectReportPrefetched'
const ANALYSIS_ENTITY_STORAGE_KEY = 'checkingLearningStatus:analysisEntity'

const EXAM_TYPE_LABEL_MAP = {
  1: '单元测试',
  2: '统考联考',
  3: '校内考试'
}

const DEFAULT_KNOWLEDGE_COLORS = ['#0ED1AD', '#F3BF7E', '#FB850A', '#FA5940']

export const getSubjectDifficulty = ({ examId, examType, courseId, scoreId }) => {
  if (!examId) throw new Error('[getSubjectDifficulty] examId不能为空')
  if (examType === undefined || examType === null || `${examType}`.trim() === '') throw new Error('[getSubjectDifficulty] examType不能为空')
  if (!courseId) throw new Error('[getSubjectDifficulty] courseId不能为空')
  if (!scoreId) throw new Error('[getSubjectDifficulty] scoreId不能为空')

  return http.get(API_PATHS.FIND_SUBJECT_DIFFICULTY, {
    examId,
    examType,
    courseId,
    scoreId
  })
}

export const getKnowledgePointAnalysis = ({ scoreId, lId }) => {
  if (!scoreId) throw new Error('[getKnowledgePointAnalysis] scoreId不能为空')
  if (!lId) throw new Error('[getKnowledgePointAnalysis] l_id不能为空')

  return http.get(API_PATHS.GET_KNOWLEDGE_ANALYSIS, {
    scoreId,
    l_id: lId
  })
}

export const getTeacherComment = ({ examId, examType, courseId }) => {
  if (!examId) throw new Error('[getTeacherComment] examId不能为空')
  if (examType === undefined || examType === null || `${examType}`.trim() === '') throw new Error('[getTeacherComment] examType不能为空')
  if (!courseId) throw new Error('[getTeacherComment] courseId不能为空')

  return http.get(API_PATHS.FIND_XDJP_FOR_COURSE, {
    examId,
    examType,
    courseId
  })
}

export const mapSubjectDifficulty = (response = {}) => {
  const entity = response?.entity || {}

  const myList = Array.isArray(entity.listVOs)
    ? entity.listVOs
    : Array.isArray(entity.resultList)
      ? entity.resultList
      : []

  const avgSource = entity.listVO || entity.listVo || entity.avgList
  const avgList = Array.isArray(avgSource)
    ? avgSource
    : Array.isArray(avgSource?.list)
      ? avgSource.list
      : []

  const avgMap = new Map()

  avgList.forEach((item) => {
    if (!item) return
    const key = item.key || item.subject_difficulty_name || item.difficulty_name || item.difficulty
    if (!key) return
    const rate = item.score_rate ?? item.score_rate_avg ?? item.avgRate ?? item.avg_rate
    if (rate === undefined || rate === null) return
    avgMap.set(key, Number(rate) || 0)
  })

  return myList.map((item, index) => {
    const difficulty = item.subject_difficulty_name || item.difficulty_name || item.difficulty || `难度${index + 1}`
    const key = item.key || difficulty
    const myRate = Number(item.score_rate ?? item.myRate ?? item.my_rate ?? 0)
    const avgRate = avgMap.has(key)
      ? avgMap.get(key)
      : Number(item.score_rate_avg ?? item.avgRate ?? item.avg_rate ?? 0)

    return {
      id: item.id || index,
      difficulty,
      myRate,
      avgRate
    }
  })
}

export const mapKnowledgeAnalysis = (response = {}) => {
  const entity = response?.entity

  // 兼容多种返回结构：entity 为数组，或 entity.list / entity.resultList 为数组
  const list = Array.isArray(entity)
    ? entity
    : Array.isArray(entity?.list)
      ? entity.list
      : Array.isArray(entity?.resultList)
        ? entity.resultList
        : []

  const knowledgeData = list.map((item, index) => ({
    id: item.id || index,
    name: item.name || item.knowledge_name || `知识点${index + 1}`,
    value: Number(item.rate ?? item.percent ?? 0),
    color: item.color || DEFAULT_KNOWLEDGE_COLORS[index % DEFAULT_KNOWLEDGE_COLORS.length],
    detail: item.detail || item.description || ''
  }))

  // 优先使用接口返回的 entity.good_num；若无，则回退到基于数据的推算
  const masteredCountFromApi = entity && entity.good_num !== undefined && entity.good_num !== null
    ? Number(entity.good_num) || 0
    : null

  const masteredCount = masteredCountFromApi !== null
    ? masteredCountFromApi
    : knowledgeData.reduce((count, item) => {
        const flag = item.value >= 100 || item.detail?.includes('已掌握') || false
        return flag ? count + 1 : count
      }, 0)

  // 固定三项 legend 数据，颜色与名称固定，百分比与详情从接口可选读取
  const toPercentNumber = (raw) => {
    if (raw === undefined || raw === null) return 0
    if (typeof raw === 'number' && Number.isFinite(raw)) {
      return raw <= 1 ? Math.round(raw * 100) : Math.round(raw)
    }
    const str = String(raw).trim()
    if (!str) return 0
    // 允许传入 '30%'、'30.5%'、'0.3'、'30' 等
    const parsed = parseFloat(str.replace('%', ''))
    if (!Number.isFinite(parsed)) return 0
    return parsed <= 1 ? Math.round(parsed * 100) : Math.round(parsed)
  }

  const extractNames = (rawList) => {
    if (!Array.isArray(rawList)) return ''
    const names = []
    rawList.forEach((entry) => {
      if (!entry) return
      if (typeof entry === 'string') {
        names.push(entry)
        return
      }
      if (Array.isArray(entry)) {
        entry.forEach((sub) => {
          if (typeof sub === 'string') names.push(sub)
          else if (sub && typeof sub === 'object') {
            Object.values(sub).forEach((val) => {
              if (typeof val === 'string') names.push(val)
            })
          }
        })
        return
      }
      if (typeof entry === 'object') {
        Object.values(entry).forEach((val) => {
          if (typeof val === 'string') names.push(val)
        })
      }
    })
    return names.join(' ')
  }

  const legendData = [
    {
      key: 'good',
      name: '已掌握知识点',
      color: '#2676FF',
      value: toPercentNumber(entity?.already_mastered),
      detail: extractNames(entity?.goodlist) || entity?.good_desc || ''
    },
    {
      key: 'bad',
      name: '未掌握知识点',
      color: '#FF4949',
      value: toPercentNumber(entity?.not_fully_grasp),
      detail: extractNames(entity?.qianlist) || entity?.bad_desc || ''
    }
  ]

  return {
    masteredCount,
    knowledgeData,
    legendData
  }
}

export const mapTeacherComment = (xdjpRes = {}) => {
  const entity = xdjpRes?.entity
  if (entity === undefined || entity === null || entity === '') {
    return {
      content: '暂无点评'
    }
  }

  return {
    content: typeof entity === 'string'
      ? entity
      : (entity.xdjp ?? entity.comment ?? '暂无点评')
  }
}

const storeSubjectReportPayload = (payload) => {
  uni.setStorageSync(SUBJECT_REPORT_STORAGE_KEY, payload)
}

const getStoredAnalysisEntity = () => {
  return uni.getStorageSync(ANALYSIS_ENTITY_STORAGE_KEY) || null
}

const getExamTypeLabel = (examType) => EXAM_TYPE_LABEL_MAP[examType] || ''

export const prefetchSubjectReport = async ({
  examId,
  examType,
  courseId,
  scoreId,
  lId,
  xdjpRes,
  subjectName = '',
  examName = '',
  subjectScore,
  subjectFullScore
} = {}) => {
  if (!examId) throw new Error('[prefetchSubjectReport] examId为空')
  if (examType === undefined || examType === null || `${examType}`.trim() === '') throw new Error('[prefetchSubjectReport] examType为空')
  if (!courseId) throw new Error('[prefetchSubjectReport] courseId为空')
  if (!scoreId) throw new Error('[prefetchSubjectReport] scoreId为空')
  if (!lId) throw new Error('[prefetchSubjectReport] l_id为空')

  const [scoreInfoRes, difficultyRes, knowledgeRes, teacherCommentRes] = await Promise.all([
    findStudentScoreInfo({ examId, courseId }),
    getSubjectDifficulty({ examId, examType, courseId, scoreId }),
    getKnowledgePointAnalysis({ scoreId, lId }),
    xdjpRes ? Promise.resolve(xdjpRes) : getTeacherComment({ examId, examType, courseId })
  ])

  console.log('单科报告-成绩信息:', scoreInfoRes)
  console.log('单科报告-难易得分率:', difficultyRes)
  console.log('单科报告-知识点分析:', knowledgeRes)
  console.log('单科报告-小董老师点评:', teacherCommentRes)

  const payload = {
    examId,
    examType,
    courseId,
    scoreId,
    lId,
    subjectScore,
    subjectFullScore,
    scoreInfoRes,
    difficultyRes,
    knowledgeRes,
    teacherCommentRes,
    xdjpRes,
    meta: {
      subjectName,
      examName
    }
  }

  storeSubjectReportPayload(payload)
  return payload
}

export const restoreSubjectReport = () => {
  return uni.getStorageSync(SUBJECT_REPORT_STORAGE_KEY) || null
}

export const clearSubjectReport = () => {
  uni.removeStorageSync(SUBJECT_REPORT_STORAGE_KEY)
}

export const buildSubjectReportViewData = (payload) => {
  if (!payload) return null

  const analysisEntity = getStoredAnalysisEntity()
  const scoreInfo = mapScoreInfoData(payload.scoreInfoRes)
  const difficulty = mapSubjectDifficulty(payload.difficultyRes)
  const knowledge = mapKnowledgeAnalysis(payload.knowledgeRes)
  const teacherComment = mapTeacherComment(payload.teacherCommentRes || payload.xdjpRes)

  const subjectScore = payload.subjectScore ?? scoreInfo.totalScore
  const subjectFullScore = payload.subjectFullScore ?? scoreInfo.totalScoreSum

  const examInfo = {
    id: payload.examId,
    title: payload.meta?.examName || analysisEntity?.exam_name || '',
    category: payload.meta?.subjectName || '',
    range: getExamTypeLabel(payload.examType ?? analysisEntity?.examType),
    date: analysisEntity?.exam_time || ''
  }

  const userInfo = {
    totalScore: subjectScore !== undefined && subjectScore !== null
      ? Number(subjectScore).toFixed(1)
      : Number(scoreInfo.totalScore ?? 0).toFixed(1),
    totalScoreSum: subjectFullScore ?? scoreInfo.totalScoreSum ?? 0,
    gradeRank: scoreInfo.gradeRank ?? null,
    classRank: scoreInfo.classRank ?? null
  }

  return {
    examInfo,
    userInfo,
    subjectScore,
    subjectFullScore,
    difficultyData: difficulty,
    knowledgeData: knowledge.knowledgeData,
    masteredCount: knowledge.masteredCount,
    knowledgeLegendData: knowledge.legendData,
    teacherComment
  }
}

export const useSubjectReportApi = () => ({
  getSubjectDifficulty,
  getKnowledgePointAnalysis,
  getTeacherComment,
  mapSubjectDifficulty,
  mapKnowledgeAnalysis,
  mapTeacherComment,
  prefetchSubjectReport,
  restoreSubjectReport,
  clearSubjectReport,
  buildSubjectReportViewData
})

export default {
  getSubjectDifficulty,
  getKnowledgePointAnalysis,
  getTeacherComment,
  mapSubjectDifficulty,
  mapKnowledgeAnalysis,
  mapTeacherComment,
  prefetchSubjectReport,
  restoreSubjectReport,
  clearSubjectReport,
  buildSubjectReportViewData,
  useSubjectReportApi
}
